import {
  getActivityListDetail,
  getListDetail,
  getUserRecord,
  getChainRecord,
  transFormActivityById,
} from "@/api/modules/chain";
import DateUtil from "@/mixins/date";
import {
  Component,
  Vue
} from "vue-property-decorator";

@Component({})
export default class chain extends Vue {

  name = "chain";

  /** 获取活动详情 */
  activityDetail = {} as any

  /** 活动商品数组 */
  activityList = []

  /** 活动信息 */
  countDetail = {} as any
  /** 倒计时 */
  timeData = {}
  /** 倒计时状态 */
  state = ""

  /** 规格弹窗 */
  showVisible = false

  /** 规格操作暂存对象 */
  currentItem = {}

  /** 商品总价 */
  totalPrice = 0 || '0'

  /** 选择商品总数 */
  goodNum = 0

  /** 用户购买记录 */
  buyQuery = {}

  /** 参与接龙 */
  joinList = []

  page = 1
  size = 10
  /** 是否有更多数据 */
  hasMore = true

  /** 是否有分页数据 */
  hasListMore = true

  /** 商品分页数据 */
  goodQuery: any = {
    page: 1,
    size: 10,
  }

  /** 是否有授权 */
  authType = false

  /** 跳转携带参数 */
  options = {} as any

  actId = ""

  hasChainAct = false

  bottomType = true

  bottomHeight = 46
  showCountDown = false
  remainTime = 0
  getActivitytype = false

  getHeight() {
    let bottomHeight = this.bottomHeight;
    uni.getSystemInfo({
      success: res => {
        if (res.model.indexOf("iPhone X") > -1) {
          bottomHeight = 80;
          this.bottomHeight = bottomHeight;
        }
      },
    });
  }

  getPosition(type: any) {
    this.bottomType = Boolean(type)
  }

  getActivity(id: any) {
    getActivityListDetail(id, {})
      .then(res => {
        const countDownInfo = this.getCountDownInfo(res);
        this.dealTime(countDownInfo);
        const now = Date.now();
        const end = Date.parse(res.endTime);
        if (now > end) {
          const culTime = now - end;
          const h = culTime / 3600000;
          const m = (culTime % (1000 * 60 * 60)) / (1000 * 60);
          if (h > 24) {
            const now = new Date().getTime();
            const stop = new Date(res.endTime.replace(/-/g, "/")).getTime();
            let day = ((now - stop) / 1000 / 24 / 60 / 60) as any;
            day = day.toFixed(0);
            res.stopTime = `${day}天前`;
          } else if (h > 1) {
            res.stopTime = `${h.toFixed(0)}小时前`;
          } else if (m > 0) {
            res.stopTime = `${m.toFixed(0)}分钟前`;
          }
        }
        this.activityDetail = res
        this.totalPrice = "0.00"
        this.goodNum = 0
        this.getActivitytype = false
      }).catch(()=>{
        this.getActivitytype = false
      }).finally(()=>{
        this.getBuyerRecord();
        this.getAllChain();
        this.getListDetail();
      })
  }

  /**
   * 获取商品数组详情
   */
  getListDetail() {
    const goodQuery = this.goodQuery;
    const activityDetail = this.activityDetail;
    const idList = activityDetail.apiSolitaireActivityProductVos;
    const ids = idList.map((item: { productId: any; }) => item.productId).join(",");
    const param = {
      current: goodQuery.page,
      distributionMode: 1, // (0–商家配送，1–快递配送)
      size: goodQuery.size,
      productType: activityDetail.productType,
      productIds: ids,
    };
    getListDetail(param)
      .then(res => {
        if (res.list.length === 0) {
          this.hasListMore = false
          return;
        }
        res.list.forEach((item: any) => {
          item.skuStocks.forEach((cItem: any) => {
            cItem.isCheck = false;
            cItem.price = cItem.price.toFixed(2);
            cItem.originalPrice = cItem.originalPrice.toFixed(2);
          });
          item.allStock = item.skuStocks.reduce((per: any, tItem: { stock: any; }) => {
            return per + tItem.stock;
          }, 0);
          item.skuStocks[0].isCheck = true;
          item.actStocks = item.skuStocks[0];
          item.actStocks.goodNum = 0;
        });
        const list = this.activityList;
        this.hasListMore = true
        this.activityList = list.concat(res.list)
      })
      .catch(err => {
        console.log("err", err);
      });
  }

  /**
   * 点击复制接龙链接
   */
  clickCopy() {
    const userInfo = this.$store.state.userStore.userInfo;
    const tenantId = userInfo.tenantId;
    const url = `https://test.superprism.cn/h5?tenanId=${tenantId}`;
    const param = {
      path: url,
    };
    transFormActivityById(this.actId, param).then(res => {
      uni.setClipboardData({
        data: res,
        success: () => {
          uni.showToast({
            title: "复制成功",
          });
        },
      });
    });
  }

  /**
   * 获取用户购买记录
   */
  getBuyerRecord() {
    const param = {
      solitaireActivityId: this.actId,
    };
    getUserRecord(param)
      .then(res => {
        res.forEach((item: { receiverPhone: string; payTime: string | Date | number; }) => {
          item.receiverPhone = item.receiverPhone.replace(
            /(\d{3})\d{4}(\d{4})/,
            "$1****$2",
          );
          item.payTime =
            Number(new DateUtil("").getD(new Date())) -
              Number(new DateUtil("").getD(item.payTime)) >
              0
              ? `${Number(new DateUtil("").getD(new Date())) -
              Number(new DateUtil("").getD(item.payTime))}天前`
              : new DateUtil("").getHM(item.payTime);
        });
        this.buyQuery = res
      })
      .catch(err => {
        console.log(err);
      });
  }

  /**
   * 获取接龙记录
   */
  getAllChain() {
    const param = {
      solitaireActivityId: this.actId,
      current: this.page,
      size: this.size,
    };
    getChainRecord(param).then(res => {
      if (res.list.length === 0) {
        this.hasMore = false
        return;
      }
      let list = this.joinList;
      list = list.concat(res.list);
      this.joinList = list
    });
  }

  /**
   * 查看更多接龙记录
   */
  showMore() {
    if (!this.hasMore) {
      return;
    }
    this.page = this.page + 1
    this.getAllChain();
  }

  /**
   * 点击选择规格
   */
  clickSku(e: { currentTarget: { dataset: { item: any; }; }; }) {
    const currentItem = e.currentTarget.dataset.item;
    currentItem.skuStocks.forEach((cItem: { isCheck: boolean; id: any; }) => {
      cItem.isCheck = false;
      if (cItem.id === currentItem.actStocks.id) {
        cItem.isCheck = true;
      }
    });
    this.showVisible = true
    this.currentItem = currentItem
  }

  /**
   * 弹窗修改规格
   */
  selectSku(e: { currentTarget: { dataset: { skuitem: any; }; }; }) {
    const skuItem = e.currentTarget.dataset.skuitem;
    if (skuItem.stock === 0) {
      uni.showToast({
        title: "此规格暂无库存",
        icon: "none",
      });
      return;
    }
    const currentItem = this.currentItem as any;
    currentItem.skuStocks.forEach((cItem: { isCheck: boolean; id: any; }) => {
      cItem.isCheck = false;
      if (skuItem.id === cItem.id) {
        cItem.isCheck = !cItem.isCheck;
      }
      if (cItem.isCheck) {
        currentItem.actStocks = skuItem;
        currentItem.actStocks.goodNum = 0;
      }
    });
    const activityList = this.activityList;
    activityList.forEach((aItem: { id: any; actStocks: any; }) => {
      if (aItem.id === currentItem.id) {
        aItem.actStocks = currentItem.actStocks;
      }
    });
    this.activityList = activityList
    this.currentItem = currentItem
  }

  /**
   * 关闭规格
   */
  onClose() {
    this.showVisible = false
  }

  /**
   * 增加购物车数量
   */
  increase(e) {
    const item = e.currentTarget.dataset.item;
    const list = this.activityList;
    if (
      item.actStocks.perLimit > 0 &&
      item.actStocks.goodNum + 1 > item.actStocks.perLimit
    ) {
      uni.showToast({
        title: "商品已达限购",
        icon: "none",
      });
      return;
    }
    if (item.actStocks.goodNum + 1 > item.actStocks.stock) {
      uni.showToast({
        title: "商品库存不足",
        icon: "none",
      });
      return;
    }
    list.forEach((aItem) => {
      if (aItem.id === item.id) {
        aItem.actStocks.goodNum =aItem.actStocks.goodNum + 1;
      }
    });
    this.activityList = list
    this.getTotalPrice();
  }

  /**
   * 减少商品数量
   */
  decrease(e) {
    const item = e.currentTarget.dataset.item;
    const list = this.activityList;
    if (item.actStocks.goodNum - 1 < 0) {
      return;
    }
    list.forEach((aItem: { id: any; actStocks: { goodNum: number; }; }) => {
      if (aItem.id === item.id) {
        aItem.actStocks.goodNum -= 1;
      }
    });
    this.activityList = list
    this.getTotalPrice();
  }

  /**
   * 算取总价
   */
  getTotalPrice() {
    if (this.countDetail.status === "ended") {
      return;
    }
    let total = 0;
    let goodNum = 0;
    const list = this.activityList;
    list.forEach((item: { actStocks: { goodNum: number; }; }) => {
      if (item.actStocks.goodNum < 0) {
        item.actStocks.goodNum = 0;
      }
    });
    list.reduce((preVal: number, item: { actStocks: { goodNum: number; price: any; }; }) => {
      return (total = preVal + item.actStocks.goodNum * Number(item.actStocks.price));
    }, total);

    list.reduce((preVal: any, item: { actStocks: { goodNum: any; }; }) => {
      return (goodNum = preVal + item.actStocks.goodNum);
    }, goodNum);

    this.totalPrice = total.toFixed(2)
    this.goodNum = goodNum
  }

  /**
   * 点击提交订单
   */
  submit() {
    if (this.countDetail.status !== "beginning") {
      return;
    }
    const userInfo = this.$store.state.userStore.userInfo;
    if (!userInfo.whetherAuthorization) {
      this.authType = true
      return;
    }
    const apiProductVos = this.activityList;
    const items = apiProductVos
      .filter((aItem: { actStocks: { goodNum: number; }; }) => aItem.actStocks.goodNum > 0)
      .map((inItem: { activityProductId: any; dominoState: any; actStocks: { goodNum: any; id: any; }; }) => {
        return {
          solitaireActivityId: this.actId,
          activityProductId: inItem.activityProductId,
          dominoState: inItem.dominoState,
          number: inItem.actStocks.goodNum,
          skuId: inItem.actStocks.id,
        };
      });
    if (!items.length) {
      uni.showToast({
        title: "请先选择商品",
        icon: "none",
      });
      return;
    }
    uni.navigateTo({
      url: `/modules/pages/submit/submit?items=${encodeURIComponent(
        JSON.stringify(items),
      )}`,
    });
  }

  /**
   * 获取倒计时
   */
  getCountDownInfo(item: { startTime: string; endTime: string; }) {
    const dateNow = Date.now();
    const activityBeginTime = new Date(
      item.startTime.replace(/-/g, "/"),
    ).getTime();
    const activityEndTime = new Date(item.endTime.replace(/-/g, "/")).getTime();
    const aboutToBegin = dateNow < activityBeginTime; // 将要开始
    const isBegin = dateNow >= activityBeginTime && dateNow < activityEndTime; // 已开始
    const isEnd = dateNow >= activityEndTime; // 已结束
    let toBeginTime = activityBeginTime - dateNow;
    let toEndTime = activityEndTime - dateNow;
    let remainTime = 0; //
    let status = "";

    if (aboutToBegin) {
      status = "aboutToBegin";
      remainTime = toBeginTime;
    }
    if (isBegin) {
      status = "beginning";
      toBeginTime = 0;
      remainTime = toEndTime;
    }
    if (isEnd) {
      status = "ended";
      toEndTime = 0;
      remainTime = 0;
      this.timeData = {
        hours: this.formatNumber('0'),
        minutes: this.formatNumber('0'),
        seconds: this.formatNumber('0'),
      }
    }

    return {
      status,
      remainTime,
      toBeginTime,
      toEndTime,
    };
  }

  /**
   * 格式化时间
   * @param n
   */
  formatNumber(n: string | any[]) {
    n = n.toString();
    return n[1] ? n : "0" + n;
  }

  /**
   * 获取时间信息
   */
  dealTime(options: { status: any; remainTime: any; toBeginTime?: number; toEndTime: any; timeData?: any; }) {
    if (options.status === "aboutToBegin") {
      this.countDetail.status = "aboutToBegin"
      this.countDetail.toBeginTime = 0
      this.countDetail.toEndTime = options.toEndTime - options.remainTime
    }

    if (options.status === "beginning") {
      this.countDetail.status = "beginning"
      this.countDetail.toBeginTime = 0
      this.countDetail.toEndTime = 0
    }

    if (options.status === "ended") {
      this.countDetail.status = "ended"
      this.countDetail.toBeginTime = 0
      this.countDetail.toEndTime = 0
    }

    this.timeData = options.timeData
    this.remainTime = options.remainTime
    // showCountDown: options.remainTime ? true : false,
    this.showCountDown = true
  }

  /**
   * 倒计时变化
   * @param e
   */
  handleChange(e) {
    const { days, hours, minutes, seconds } = e;
    const h = hours + days * 24;
    // h = h > 99 ? 90 : h;
    this.timeData = {
      hours: this.formatNumber(h),
      minutes: this.formatNumber(minutes),
      seconds: this.formatNumber(seconds),
    }

    if (h === 0 && minutes === 0 && seconds === 0) {
      this.activityList = []
      this.hasListMore = false
      this.getActivity(this.actId);
    }
  }

  /**
   * 点击进入商品详情
   */
  jumpDetail(e: { currentTarget: { dataset: { item: { id: any; }; }; }; }) {
    return;
    const id = e.currentTarget.dataset.item.id;
    uni.navigateTo({
      url: `/pages/detail/detail?id=${id}`,
    });
  }
}
